import { defineStore } from "pinia";
import * as apis from "@/apis/auth";

type Auth = ({ status: "ok" } & Me) | ({ status: "failed" | "loading" } & Partial<Me>);

type States = {
  auth: Auth;
};

type Actions = {
  load: () => void;
  login: (username: string, password: string) => Promise<{ ok: true } | { ok: false; message: string }>;
  logout: () => void;
};

const useAuthStore = defineStore<"me", States, {}, Actions>("me", {
  state: () => ({ auth: { status: "loading" } }),
  actions: {
    async load() {
      try {
        this.auth = { status: "loading" };
        const me = await apis.profile();
        this.auth = { status: "ok", ...me };
      } catch (err) {
        console.log("get profile failed", err);
        this.auth = { status: "failed" };
      }
    },
    async login(username: string, password: string) {
      try {
        this.auth = { status: "loading" };
        const me = await apis.login({ username, password });
        this.auth = { status: "ok", ...me };
        return { ok: true };
      } catch (err) {
        this.auth = { status: "failed" };
        return { ok: false, message: (err as Error).message };
      }
    },
    async logout() {
      await apis.logout();
      this.auth = { status: "failed" };
    },
  },
});

export default useAuthStore;
